﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.IO;
using System.Runtime.Serialization;
using System.ServiceModel;
using WebUI.SmartDatingRef;

namespace SvcUtils {
    /// <summary>
    /// Cryptographic procedures used throughout the service.
    /// Instances of this class are not meant to be created.
    /// </summary>
    public sealed class CryptoImpl {
        private CryptoImpl() {
        }

        /// <summary>
        /// Generates a cryptographically random session key
        /// </summary>
        /// <returns>session key of KEY_SIZE bits</returns>
        public static byte[] getSessionKey() {
            byte[] sessionKey = new byte[Constants.KEY_SIZE / 8];
            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()) {
                rng.GetBytes(sessionKey);
            }
            return sessionKey;
        }

        /// <summary>
        /// Prepares a cryptographic AES stream of the right format and
        /// mode (read/write).
        /// </summary>
        /// <param name="aes">AES cipher</param>
        /// <param name="sessionKey">session key</param>
        /// <param name="storage">backing memory stream</param>
        /// <param name="mode">mode (read/write)</param>
        /// <returns></returns>
        public static CryptoStream getAesCryptoStream(Aes aes, byte[] sessionKey,
        MemoryStream storage, CryptoStreamMode mode) {
            aes.IV = Constants.ENCRYPTION_IV;
            aes.KeySize = Constants.KEY_SIZE;
            using (Rfc2898DeriveBytes rfcBytes =
                new Rfc2898DeriveBytes(sessionKey, Constants.SALT, Constants.ITERATIONS)) {
                aes.Key = rfcBytes.GetBytes(aes.KeySize / 8);
            }

            ICryptoTransform transform = (mode == CryptoStreamMode.Write) ?
                aes.CreateEncryptor(aes.Key, aes.IV) :
                aes.CreateDecryptor(aes.Key, aes.IV);
            return new CryptoStream(storage, transform, mode);
        }

        /// <summary>
        /// Encrypts data provided using AES
        /// </summary>
        /// <param name="data">data to encrypt</param>
        /// <param name="sessionKey">encryption key</param>
        /// <returns></returns>
        public static byte[] cryptAes(byte[] data, byte[] sessionKey) {
            byte[] cryptedData;
            using (Aes aes = Aes.Create()) {
                MemoryStream stream = new MemoryStream();
                CryptoStream cryptoStream = getAesCryptoStream(aes,
                        sessionKey, stream, CryptoStreamMode.Write);
                cryptoStream.Write(data, 0, data.Length);
                cryptoStream.FlushFinalBlock();
                cryptedData = stream.ToArray();
                cryptoStream.Close();
                stream.Close();
            }
            return cryptedData;
        }

        /// <summary>
        /// Decrypts data provided using AES
        /// </summary>
        /// <param name="encryptedData">encrypted data</param>
        /// <param name="sessionKey">decryption key</param>
        /// <returns></returns>
        public static byte[] decryptAes(byte[] encryptedData, byte[] sessionKey) {
            byte[] decryptedBytes = new byte[encryptedData.Length];
            using (Aes aes = Aes.Create()) {
                MemoryStream stream = new MemoryStream(encryptedData);
                CryptoStream cryptoStream = getAesCryptoStream(aes,
                           sessionKey, stream, CryptoStreamMode.Read);
                int decryptedLength = cryptoStream.Read(decryptedBytes, 0,
                    encryptedData.Length);
                Array.Resize(ref decryptedBytes, decryptedLength);
                cryptoStream.Close();
                stream.Close();
            }
            return decryptedBytes;
        }

        /// <summary>
        /// Returns sha-1 digest of the byte stream provided
        /// </summary>
        /// <param name="data">data to get hash of</param>
        /// <returns>sha1(data)</returns>
        public static byte[] sha1(byte[] data) {
            using (SHA1 sha1 = SHA1.Create()) {
                return sha1.ComputeHash(data);
            }
        }

        /// <summary>
        /// Extracts session key from PKCS1.5-compliant RSA-encrypted key exchange stream
        /// (PKCS padding type = 2)
        /// </summary>
        /// <param name="encryptedSessionKey">PKCS1.5-compliant message with session key</param>
        /// <returns></returns>
        public static byte[] extractKeyFromPKCS1Exchange(byte[] encryptedSessionKey) {
            const int AT_KEYEXCHANGE = 1;
            CspParameters cspParams = new CspParameters();
            cspParams.KeyContainerName = "key_exchange_container";
            cspParams.KeyNumber = AT_KEYEXCHANGE;
            byte[] sessionKey = null;
            using (RSACryptoServiceProvider rsaServerSide = new
                RSACryptoServiceProvider(cspParams)) {
                rsaServerSide.PersistKeyInCsp = true;
                rsaServerSide.FromXmlString(Constants.SERVER_KEYS);

                AsymmetricKeyExchangeDeformatter asymDeformatter =
                    new RSAPKCS1KeyExchangeDeformatter(rsaServerSide);
                sessionKey = asymDeformatter.DecryptKeyExchange(encryptedSessionKey);
            }
            return sessionKey;
        }

        /// <summary>
        /// Restores object of type T from previously encrypted representation obtained
        /// by call to writeObjectEncrypted<T>().
        /// </summary>
        /// <typeparam name="T">any class which has DataContract attribute applied</typeparam>
        /// <param name="encryptedBytes">encrypted bytes representing the object</param>
        /// <param name="key">encryption key</param>
        /// <returns>object restored from encrypted bytes</returns>
        public static T readObjectEncrypted<T>(byte[] encryptedBytes, byte[] key) {
            using (Aes aes = Aes.Create()) {
                using (MemoryStream storage = new MemoryStream(encryptedBytes)) {
                    using (CryptoStream cryptoStream = getAesCryptoStream(aes, key,
                        storage, CryptoStreamMode.Read)) {
                        if (typeof(T) == typeof(PersonalData)) {
                            return (T)PDSerializer.ReadObject(cryptoStream);
                        } else {
                            DataContractSerializer dcs = new DataContractSerializer(typeof(T));
                            return (T)(dcs.ReadObject(cryptoStream));
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Serializes object of type T to the encrypted stream and returns the encrypted bytes.
        /// </summary>
        /// <typeparam name="T">any class which has DataContract attribute applied</typeparam>
        /// <param name="obj">object of type T</param>
        /// <param name="key">encryption key</param>
        /// <returns>encrypted XML representation of the object</returns>
        public static byte[] writeObjectEncrypted<T>(T obj, byte[] key) {
            using (MemoryStream storage = new MemoryStream()) {
                using (Aes aes = Aes.Create()) {
                    CryptoStream cryptoStream = getAesCryptoStream(aes,
                        key, storage, CryptoStreamMode.Write);

                    if (typeof(T) == typeof(PersonalData)) {
                        PDSerializer.WriteObject(cryptoStream, obj);
                    } else {
                        DataContractSerializer dcs = new DataContractSerializer(typeof(T));
                        dcs.WriteObject(cryptoStream, obj);
                    }
                    if (!cryptoStream.HasFlushedFinalBlock)
                        cryptoStream.FlushFinalBlock();
                }
                return storage.ToArray();
            }
        }

        /// <summary>
        /// Generates PKCS1.5-compliant, blocktype=2 key exchange stream
        /// </summary>
        /// <param name="sessionKey">session key to exchange with the service</param>
        /// <returns>encrypted key exchange</returns>
        public static byte[] rsaForKeyExchange(byte[] sessionKey) {
            const int AT_KEYEXCHANGE = 1;
            CspParameters cspParams = new CspParameters();
            cspParams.KeyContainerName = "key_exchange_container";
            cspParams.KeyNumber = AT_KEYEXCHANGE;

            byte[] encryptedSessionKey;
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspParams)) {
                rsa.FromXmlString(Constants.SERVER_KEYS);
                AsymmetricKeyExchangeFormatter formatter = new
                                                   RSAPKCS1KeyExchangeFormatter(rsa);
                encryptedSessionKey = formatter.CreateKeyExchange(sessionKey);
            }
            return encryptedSessionKey;
        }
    }
}